/**
 * 
 */
package com.kelaite.procurement.restful;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.kelaite.procurement.constants.Constants;
import com.kelaite.procurement.dto.UserDTO;
import com.kelaite.procurement.exception.BusinessException;

/**
 * @author yuanchangwei
 *
 */
public abstract class BaseController {

	protected final Logger logger = Logger.getLogger(getCurrentClass());

	/**
	 * 获取具体的运行时class，用于记录日志
	 * 
	 * @return
	 */
	protected abstract Class<?> getCurrentClass();

	/**
	 * 如果用户登录，用于获取当前登录用户相关信息
	 * 
	 * @param session
	 * @return
	 * @throws Exception
	 */
	protected UserDTO getCurrentUser(HttpSession session) throws Exception {

		if (null == session) {
			throw new BusinessException("session is null. ");
		}
		UserDTO user = (UserDTO) session.getAttribute(Constants.CURRENT_USER);
		if (null != user) {
			return user;
		}
		String errMsg = "user is null. ";
		logger.error(errMsg);
		throw new BusinessException(errMsg);
	}

	/**
	 * 如果用户登录，用于获取当前登录用户的用户名
	 * 
	 * @param session
	 * @return
	 * @throws Exception
	 */
	protected String getCurrentUsername(HttpSession session) throws Exception {

		UserDTO user = getCurrentUser(session);
		return user.getUsername();
	}

	/**
	 * 如果执行此Controller里面的方法出现异常,则会执行该方法
	 * 
	 * @param e
	 * @return
	 */
	@ExceptionHandler({ Exception.class })
	public ModelAndView exceptionHandle(Exception e) {

		ModelAndView model = new ModelAndView("error");
		model.addObject("exception", "Exception===>" + e);
		return model;
	}
}
